from fastapi import APIRouter, Depends, HTTPException, status, Query
from typing import List, Optional
from app.models.notification import (
    NotificationCreate,
    NotificationUpdate,
    NotificationListResponse,
    UnreadCountResponse,
    BatchDeleteRequest
)
from app.services.notification_service import NotificationService
from app.api.v1.routes.auth import get_current_user
from app.services.user_service import UserInDB
from app.utils.permissions import require_permissions
import logging

logger = logging.getLogger(__name__)
router = APIRouter()
notification_service = NotificationService()

@router.post("/", response_model=dict, tags=["通知管理"])
@require_permissions(["notification_manage"])
async def create_notification(
    notification: NotificationCreate,
    current_user: UserInDB = Depends(get_current_user)
):
    """创建新通知（需要通知管理权限）"""
    try:
        created_notification = notification_service.create_notification(
            notification, current_user.username
        )
        return {
            "message": "通知创建成功",
            "notification_id": created_notification.id,
            "title": created_notification.title
        }
    except Exception as e:
        logger.error(f"创建通知失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建通知失败"
        )

@router.get("/", response_model=NotificationListResponse, tags=["通知管理"])
@require_permissions(["notification_manage"])
async def get_all_notifications(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页大小"),
    current_user: UserInDB = Depends(get_current_user)
):
    """获取所有通知列表（需要通知管理权限）"""
    try:
        return notification_service.get_all_notifications(page=page, size=size)
    except Exception as e:
        logger.error(f"获取通知列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取通知列表失败"
        )

@router.put("/{notification_id}", response_model=dict, tags=["通知管理"])
@require_permissions(["notification_manage"])
async def update_notification(
    notification_id: str,
    notification: NotificationUpdate,
    current_user: UserInDB = Depends(get_current_user)
):
    """更新通知（需要通知管理权限）"""
    try:
        updated_notification = notification_service.update_notification(
            notification_id, notification
        )
        if not updated_notification:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="通知不存在"
            )
        
        return {
            "message": "通知更新成功",
            "notification_id": updated_notification.id,
            "title": updated_notification.title
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新通知失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新通知失败"
        )

@router.delete("/{notification_id}", response_model=dict, tags=["通知管理"])
@require_permissions(["notification_manage"])
async def delete_notification(
    notification_id: str,
    current_user: UserInDB = Depends(get_current_user)
):
    """删除通知（需要通知管理权限）"""
    try:
        success = notification_service.delete_notification(notification_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="通知不存在或删除失败"
            )
        
        return {"message": "通知删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除通知失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除通知失败"
        )

@router.post("/batch-delete/", response_model=dict, tags=["通知管理"])
@require_permissions(["notification_manage"])
async def batch_delete_notifications(
    request: BatchDeleteRequest,
    current_user: UserInDB = Depends(get_current_user)
):
    """批量删除通知（需要通知管理权限）"""
    try:
        success = notification_service.batch_delete_notifications(
            request.notification_ids
        )
        if not success:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="批量删除失败"
            )
        
        return {
            "message": f"成功删除 {len(request.notification_ids)} 个通知"
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"批量删除通知失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="批量删除失败"
        )

# 用户通知相关API（普通用户权限）
@router.get("/user/", response_model=NotificationListResponse, tags=["用户通知"])
@require_permissions(["notification_view"])
async def get_user_notifications(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页大小"),
    current_user: UserInDB = Depends(get_current_user)
):
    """获取当前用户的通知列表"""
    try:
        return notification_service.get_user_notifications(
            current_user.username, page=page, size=size
        )
    except Exception as e:
        logger.error(f"获取用户通知失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取通知列表失败"
        )

@router.get("/unread/", response_model=UnreadCountResponse, tags=["用户通知"])
@require_permissions(["notification_view"])
async def get_unread_count(
    current_user: UserInDB = Depends(get_current_user)
):
    """获取当前用户未读通知数量"""
    try:
        return notification_service.get_unread_count(current_user.username)
    except Exception as e:
        logger.error(f"获取未读数量失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取未读数量失败"
        )

@router.post("/{notification_id}/read/", response_model=dict, tags=["用户通知"])
@require_permissions(["notification_view"])
async def mark_notification_as_read(
    notification_id: str,
    current_user: UserInDB = Depends(get_current_user)
):
    """标记通知为已读"""
    try:
        success = notification_service.mark_as_read(
            current_user.username, notification_id
        )
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="通知不存在或标记失败"
            )
        
        return {"message": "通知已标记为已读"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"标记通知已读失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="标记已读失败"
        )
